'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var bs = require("browser-sync").create();
// default
gulp.task('default', ['clean'], $.sequence(['html', 'sass', 'js', 'img', 'jsconcat', 'jade'], 'cssSpriter'));
// watch
gulp.task('watch', ['default'], function(){
  gulp.start('server');
  gulp.watch('app/**/*.html',['html']);
  gulp.watch('app/sass/**/*.{sass,scss}', function (event) {
    $.sequence('sass', 'cssSpriter')(function () {})
  });
  gulp.watch('app/**/*.js', ['js','jsconcat']);
  gulp.watch('app/**/*.{jpg,png}', ['img']);
  gulp.watch('app/**/*.jade', ['jade']);
});
// clean dist
gulp.task('clean', function () {
  return gulp.src('./dist').pipe($.clean());
});
// html
gulp.task('html', function () {
  return gulp.src('app/**/*.html')
    .pipe(gulp.dest('dist'))
    // .pipe(bs.stream({once: true}));
})
// sass
gulp.task('sass', function () {
  return gulp.src('app/sass/**/*.{sass,scss,css}')
    .pipe($.plumber())
    .pipe($.sass())
    .pipe($.autoprefixer({
      browsers: ['last 100 versions'],
      cascade: false,
      remove:false
    }))
    .pipe($.minifyCss({
      advanced: false,
      compatibility: "ie7",
      keepBreaks: true,
      keepSpecialComments: '*'
    }))
    .pipe($.plumber.stop())
    .pipe(gulp.dest('dist/css'));
})
// js
gulp.task('js',function(){
  return gulp.src(['app/**/*.js','!app/js/lib/**/*.js'])
    .pipe(gulp.dest('dist'));
});
// jsconcat
gulp.task('jsconcat', function () {
  return gulp.src('app/js/lib/**/*.js')
    .pipe($.concat('lib.js'))
    // .pipe($.uglify())
    .pipe(gulp.dest('dist/js'));
})
// img
gulp.task('img', function () {
  return gulp.src('app/**/*.{jpg,png}')
    .pipe(gulp.dest('dist'));
})
// jade
gulp.task('jade', function () {
  return gulp.src('app/**/*.jade')
    .pipe($.jade({
      pretty: true
    }))
    .pipe(gulp.dest('dist'));
})
// cssSpriter
gulp.task('cssSpriter', function () {
  return gulp.src('./dist/css/spriter.css')
    .pipe($.cssSpriter({
      spriteSheet: './dist/img/spriter.png',
      pathToSpriteSheetFromCSS: '../img/spriter.png'
    }))
    .pipe(gulp.dest('./dist/css'))
})
// server
gulp.task('server', function () {
  bs.init({
    ui: false,
    logFileChanges: false,  // 日志信息有关更改的文件
    notify: false,          //不显示在浏览器中的任何通知。
    ghostMode: false,       // 镜像设备
    open: false,            //停止自动打开浏览器
    logPrefix: 'test',      // 改变控制台日志前缀
    port: 6686,
    server: {
      baseDir: 'dist',
      directory: true
      // index: 'page/index.html'
    },
    files: [{
      match: [
        'app/**/*.html', 
        'app/**/*.{sass,scss,css}',
        'app/**/*.js',
        'app/**/*.{jpg,png}',
        'app/**/*.jade'
      ],
      fn: function (event, file) {
        if (event === "change") {
          bs.reload();
        }
      }
    }]
  })
})